package x.ovo.wechat.bot.plugin;

import lombok.NonNull;
import org.dromara.hutool.core.text.StrUtil;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.MessageEvent;
import x.ovo.wechat.bot.core.message.TextMessage;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class TipsListener extends EventListener<MessageEvent<TextMessage>, TextMessage> {

    private final static Map<String, Long> LAST_TIP = new HashMap<>();

    public TipsListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull MessageEvent<TextMessage> event, TextMessage source) {
        // 非群消息或群成员为空，返回false
        if (!source.isGroup() || Objects.isNull(source.getMember())) return false;
        // 配置文件中不包含该成员，返回false
        if (!this.plugin.getConfig().containsKey(source.getMember().getNickName())) return false;
        // 距该成员上次发言时间未超过配置时间，返回false
        String name = source.getFrom().getNickName() + "::" + source.getMember().getNickName();
        long now = System.currentTimeMillis();
        long last = LAST_TIP.getOrDefault(name, 0L);
        long duration = Duration.ofMillis(now - last).toMinutes();
        // 更新成员发言时间
        LAST_TIP.put(name, now);
        return duration > this.plugin.<Integer>getConfig().get("tips::timeout");
    }

    @Override
    public boolean onEvent(@NonNull MessageEvent<TextMessage> event, TextMessage source) {
        String name = source.getMember().getNickName();
        String message = "@" + StrUtil.defaultIfBlank(source.getMember().getDisplayName(), name) + " " + this.plugin.<String>getConfig().get(name);
        return source.getFrom().sendMessage(message);
    }
}
